package com.huanke.iot.manage.service.device.wb;


import com.google.common.collect.Lists;
import com.huanke.iot.base.dao.customer.CustomerUserMapper;
import com.huanke.iot.base.dao.device.DeviceGroupItemMapper;
import com.huanke.iot.base.dao.device.DeviceMapper;
import com.huanke.iot.base.dao.device.DeviceTeamItemMapper;
import com.huanke.iot.base.dao.device.DeviceTeamMapper;
import com.huanke.iot.base.dao.project.ProjectMapper;
import com.huanke.iot.base.dao.user.UserManagerMapper;
import com.huanke.iot.base.dao.wb.*;
import com.huanke.iot.base.dto.wb.*;
import com.huanke.iot.base.po.customer.CustomerUserPo;
import com.huanke.iot.base.po.device.DevicePo;
import com.huanke.iot.base.po.device.group.DeviceGroupItemPo;
import com.huanke.iot.base.po.device.team.DeviceTeamItemPo;
import com.huanke.iot.base.po.device.team.DeviceTeamPo;
import com.huanke.iot.base.po.project.ProjectBaseInfo;
import com.huanke.iot.base.po.user.User;
import com.huanke.iot.base.po.wb.MaintenanceMaterial;
import com.huanke.iot.base.po.wb.MaintenanceOrder;
import com.huanke.iot.base.po.wb.MaintenanceOrderHistory;
import com.huanke.iot.base.po.wb.MaintenanceUser;
import com.huanke.iot.base.request.wb.DistributeRequest;
import com.huanke.iot.base.request.wb.FeedbackRequest;
import com.huanke.iot.base.request.wb.MaintenanceOrderRequest;
import com.huanke.iot.base.resp.project.ProjectGroupsRsp;
import com.huanke.iot.manage.service.customer.CustomerService;
import com.huanke.iot.manage.vo.request.BaseRequest;
import com.huanke.iot.manage.vo.request.customer.CustomerVo;
import com.huanke.iot.manage.vo.request.device.wb.MaintenanceMaterialRequest;
import com.huanke.iot.manage.vo.request.device.wb.MaintenanceWbUserRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Repository
@Slf4j
public class MaintenanceService {
    private static int i = 1;


    private final static String OPRATE_DISTRIBUTE = "管理员-派单";
    private final static String OPRATE_IGNORE = "管理员-忽略";
    private final static String OPRATE_REFUSE = "管理员-拒绝";
    private final static String OPRATE_FINISH = "管理员-已完成";
    private final static String OPRATE_RESOLVE = "业主-已解决";
    private final static String OPRATE_UNRESOLVE = "业主-未解决";
    private final static String WB_TEAM_NAME = "维保组";


    @Autowired
    private MaintenanceOrderMapper maintenanceOrderMapper;
    @Autowired
    private MaintenanceRecordMapper maintenanceRecordMapper;
    @Autowired
    private MaintenanceUserMapper maintenanceUserMapper;
    @Autowired
    private MaintenanceOrderHistoryMapper maintenanceOrderHistoryMapper;
    @Autowired
    private CustomerUserMapper customerUserMapper;
    @Autowired
    private UserManagerMapper userManagerMapper;
    @Autowired
    private DeviceTeamMapper deviceTeamMapper;
    @Autowired
    private DeviceTeamItemMapper deviceTeamItemMapper;
    @Autowired
    private MaintenanceMaterialMapper maintenanceMaterialMapper;
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private DeviceGroupItemMapper deviceGroupItemMapper;


    public void addOrder(MaintenanceOrderRequest request, Integer customerUserId) {
        try {
            MaintenanceUser user = getMaintenanceUser(customerUserId);

            request.setUserId(user.getId());
            MaintenanceOrder order  = new MaintenanceOrder();
            BeanUtils.copyProperties(request, order);
            order.setFaultPhoto(String.join(",",request.getFaultPhoto()));
            order.setFeedback(0);  //业主反馈状态：0初始状态，1已解决，2未解决
            order.setPreStatus(1);  //分配前，状态：1待审核（管理员待分配），2待维修，3已忽略
            order.setWbStatus(1);  //分配后，状态：0初始状态，1待维修，2待确认（管理员待审核），3已完成，4已拒绝
            order.setOrderTime(new Date()); //订单时间
            LocalDateTime now = LocalDateTime.now();
            //年月日时分秒毫秒
            String orderNo = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + afterAdd();
            order.setOrderNo(orderNo);
            order.setStatus(1);
            maintenanceOrderMapper.insert(order);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private synchronized String afterAdd() {
        if(i<999){
            i++;
        }else{
            i=1;
        }
        return String.format("%03d", i);
    }

    public List<MaintenanceOrderVo> orderlist(Integer customerUserId, Integer orderStatus) {
        List<MaintenanceOrderVo> maintenanceOrderVoList = new ArrayList<>();
        switch (orderStatus) {
            case 0:  //全部
                List<MaintenanceOrder> maintenanceOrders = maintenanceOrderMapper.selectOrderList(customerUserId, orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    getResultStatus(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            case 1:  //待维修
                List<MaintenanceOrder> maintenanceOrders1 = maintenanceOrderMapper.selectOrderList1(customerUserId, orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders1) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    Integer preStatus = maintenanceOrder.getPreStatus();
                    if(preStatus == 1){
                        maintenanceOrderVo.setResultStatus(1);
                        maintenanceOrderVo.setResultStatusMsg("待审核");
                    }else{
                        maintenanceOrderVo.setResultStatus(2);
                        maintenanceOrderVo.setResultStatusMsg("待维修");
                    }
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            case 2:   //待确认
                List<MaintenanceOrder> maintenanceOrders2 = maintenanceOrderMapper.selectOrderList2(customerUserId, orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders2) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVo.setResultStatus(3);
                    maintenanceOrderVo.setResultStatusMsg("待确认");
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            case 3:   //已完成
                List<MaintenanceOrder> maintenanceOrders3 = maintenanceOrderMapper.selectOrderList3(customerUserId, orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders3) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    Integer feedback = maintenanceOrder.getFeedback();
                    if(feedback == 2){
                        maintenanceOrderVo.setResultStatus(5);
                        maintenanceOrderVo.setResultStatusMsg("未解决");
                    }else{
                        maintenanceOrderVo.setResultStatus(4);
                        maintenanceOrderVo.setResultStatusMsg("已解决");
                    }
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            default:
                break;
        }
        return maintenanceOrderVoList;
    }

    public List<MaintenanceOrderVo> wbOrderlist(Integer customerUserId, Integer orderStatus) {
        List<MaintenanceOrderVo> maintenanceOrderVoList = new ArrayList<>();
        switch (orderStatus) {
            case 0:  //全部
                List<MaintenanceOrder> maintenanceOrders = maintenanceOrderMapper.selectWbOrderList(customerUserId, orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    getWbResultStatus(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            case 1:  //待维修
                List<MaintenanceOrder> maintenanceOrders1 = maintenanceOrderMapper.selectWbOrderList1(customerUserId, orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders1) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    getWbResultStatus(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            case 2:  //待确认
                List<MaintenanceOrder> maintenanceOrders2 = maintenanceOrderMapper.selectWbOrderList2(customerUserId, orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders2) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    getWbResultStatus(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            case 3:  //已驳回
                List<MaintenanceOrder> maintenanceOrders3 = maintenanceOrderMapper.selectWbOrderList3(customerUserId, orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders3) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    getWbResultStatus(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            case 4:  //已完成
                List<MaintenanceOrder> maintenanceOrders4 = maintenanceOrderMapper.selectWbOrderList4(customerUserId, orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders4) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    getWbResultStatus(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            default:
                break;
        }
        return maintenanceOrderVoList;
    }

    private MaintenanceOrderVo getResultStatus(MaintenanceOrder maintenanceOrder, MaintenanceOrderVo maintenanceOrderVo) {
        Integer preStatus = maintenanceOrder.getPreStatus();
        Integer wbStatus = maintenanceOrder.getWbStatus();
        switch (preStatus) {
            case 1:     //1待审核（管理员待分配），2待维修，3已忽略
                maintenanceOrderVo.setResultStatus(1);
                maintenanceOrderVo.setResultStatusMsg("待审核");
                break;
            case 2:
                switch (wbStatus) {
                    case 1:     //1待维修，2待确认（管理员待审核），3已完成，4已拒绝
                        maintenanceOrderVo.setResultStatus(2);
                        maintenanceOrderVo.setResultStatusMsg("待维修");
                        break;
                    case 2:
                        maintenanceOrderVo.setResultStatus(3);
                        maintenanceOrderVo.setResultStatusMsg("待确认");
                        break;
                    case 3:
                        Integer feedback = maintenanceOrder.getFeedback();
                        if(feedback == 2){
                            maintenanceOrderVo.setResultStatus(5);
                            maintenanceOrderVo.setResultStatusMsg("未解决");
                        }else{
                            maintenanceOrderVo.setResultStatus(4);
                            maintenanceOrderVo.setResultStatusMsg("已解决");
                        }
                        break;
                    case 4:
                        break;
                    default:
                        break;
                }
                break;
            case 3:
                maintenanceOrderVo.setResultStatus(6);
                maintenanceOrderVo.setResultStatusMsg("已忽略");
                break;
            default:
                break;
        }
        return maintenanceOrderVo;
    }

    private MaintenanceOrderVo getWbResultStatus(MaintenanceOrder maintenanceOrder, MaintenanceOrderVo maintenanceOrderVo) {
        Integer wbStatus = maintenanceOrder.getWbStatus();
        switch (wbStatus) {
            case 1:     //1待维修，2待确认（管理员待审核），3已完成，4已拒绝
                maintenanceOrderVo.setResultStatus(1);
                maintenanceOrderVo.setResultStatusMsg("待维修");
                break;
            case 2:
                maintenanceOrderVo.setResultStatus(2);
                maintenanceOrderVo.setResultStatusMsg("待确认");
                break;
            case 3:
                maintenanceOrderVo.setResultStatus(3);
                maintenanceOrderVo.setResultStatusMsg("已完成");
                break;
            case 4:
                maintenanceOrderVo.setResultStatus(4);
                maintenanceOrderVo.setResultStatusMsg("已拒绝");
                break;
            default:
                break;
        }

        return maintenanceOrderVo;
    }


    public MaintenanceOrderDetailVo orderDetail(Integer orderId) {
        MaintenanceOrder maintenanceOrder = maintenanceOrderMapper.getDetailById(orderId);
        MaintenanceOrderDetailVo maintenanceOrderDetailVo = new MaintenanceOrderDetailVo();
        BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderDetailVo);
        if(maintenanceOrder.getFaultPhoto()!=null){
            maintenanceOrderDetailVo.setFaultPhoto(Arrays.asList(maintenanceOrder.getFaultPhoto().split(",")));
        }
        if(maintenanceOrder.getResultPhoto()!=null){
            maintenanceOrderDetailVo.setResultPhoto(Arrays.asList(maintenanceOrder.getResultPhoto().split(",")));
        }
        return maintenanceOrderDetailVo;
    }

    public void userMsg(Integer customerUserId, String name, String phone) {
        MaintenanceUser maintenanceUser = new MaintenanceUser();
        maintenanceUser.setCustomerUserId(customerUserId);
        maintenanceUser.setName(name);
        maintenanceUser.setPhone(phone);
        maintenanceUser.setCreateTime(new Date());
        maintenanceUser.setRole(1);  //角色：1普通人，2维修人员，3管理人员
        maintenanceUser.setStatus(1);
        maintenanceUserMapper.insert(maintenanceUser);
    }


    public void resultPhoto(Integer orderId, List<String> resultPhoto) {
        maintenanceOrderMapper.updateResultPhoto(orderId, String.join(",", resultPhoto));
    }

    public void neglectOrder(Integer orderId) {
        maintenanceOrderMapper.neglectOrder(orderId);
    }

    public List<MaintenanceWbUserVo> obtainWbUsers() {
        List<MaintenanceWbUserVo> maintenanceWbUserVoList = new ArrayList<>();
        List<MaintenanceUser> maintenanceUsers = maintenanceUserMapper.obtainWbUsers();
        for (MaintenanceUser maintenanceUser : maintenanceUsers) {
            MaintenanceWbUserVo maintenanceWbUserVo = new MaintenanceWbUserVo();
            BeanUtils.copyProperties(maintenanceUser, maintenanceWbUserVo);
            maintenanceWbUserVoList.add(maintenanceWbUserVo);
        }
        return maintenanceWbUserVoList;
    }

    @Transactional
    public void distribute(DistributeRequest distributeRequest, Integer customerUserId) throws Exception {
        MaintenanceOrder maintenanceOrder = maintenanceOrderMapper.selectById(distributeRequest.getOrderId());
        Integer wbUserId = distributeRequest.getWbUserId();
        MaintenanceUser maintenanceUser = maintenanceUserMapper.selectById(wbUserId);
        if(maintenanceUser.getWorkStatus() == 0){
            throw new Exception("维保人员已请假");
        }
        //历史记录
        MaintenanceOrderHistory orderHistory = new MaintenanceOrderHistory();
         orderHistory.setOperateUserId(getManageMaintenanceUser(customerUserId).getId());
         orderHistory.setOrderId(distributeRequest.getOrderId());
         orderHistory.setOperateAction(OPRATE_DISTRIBUTE);
         orderHistory.setOperateDetail(distributeRequest.getDetail());
         orderHistory.setOperateTime(new Date());
         if(!addOrderHistory(orderHistory)){
             throw new Exception("派单失败");
         }
         //修改接单数
        maintenanceUser.setOrderNum(maintenanceUser.getOrderNum() + 1);
        maintenanceUserMapper.updateOrderNumAndReceiveStatus(maintenanceUser.getId(), maintenanceUser.getOrderNum());
        //给维保人员绑定设备
        DeviceTeamPo deviceTeamPo = new DeviceTeamPo();
        deviceTeamPo.setName(WB_TEAM_NAME);
        deviceTeamPo.setMasterUserId(maintenanceUser.getCustomerUserId());
        deviceTeamPo.setCreateUserId(maintenanceUser.getCustomerUserId());
        DeviceTeamPo deviceTeamPo1 = deviceTeamMapper.queryByName(deviceTeamPo);
        DeviceTeamItemPo deviceTeamItemPo = new DeviceTeamItemPo();
        Integer deviceId = maintenanceOrder.getDeviceId();
        deviceTeamItemPo.setDeviceId(deviceId);
        DevicePo devicePo = deviceMapper.selectById(deviceId);
        Integer hostDeviceId = devicePo.getHostDeviceId();
        if(hostDeviceId != null){
            deviceTeamItemPo.setDeviceId(hostDeviceId);
        }
        deviceTeamItemPo.setTeamId(deviceTeamPo1.getId());
        deviceTeamItemPo.setUserId(deviceTeamPo1.getMasterUserId());
        deviceTeamItemPo.setStatus(1);
        deviceTeamItemPo.setCreateTime(System.currentTimeMillis());
        deviceTeamItemMapper.insert(deviceTeamItemPo);

        maintenanceOrderMapper.distribute(distributeRequest.getOrderId(), wbUserId);
    }

    public List<MaintenanceOrderVo> manegeOrderlist(Integer orderStatus) {
        //0:全部 1：待分配 2：待维修  3：待审核  4：已驳回  5：已完成  6：已忽略
        List<MaintenanceOrderVo> maintenanceOrderVoList = new ArrayList<>();
        switch (orderStatus) {
            case 0:  //全部
                List<MaintenanceOrder> maintenanceOrders = maintenanceOrderMapper.selectManageOrderList(orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    getManageResultStatus(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            case 1:
                List<MaintenanceOrder> maintenanceOrders1 = maintenanceOrderMapper.selectManageOrderList1(orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders1) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    getManageResultStatus(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            case 2:
                List<MaintenanceOrder> maintenanceOrders2 = maintenanceOrderMapper.selectManageOrderList2(orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders2) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    getManageResultStatus(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            case 3:
                List<MaintenanceOrder> maintenanceOrders3 = maintenanceOrderMapper.selectManageOrderList3(orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders3) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    getManageResultStatus(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            case 4:
                List<MaintenanceOrder> maintenanceOrders4 = maintenanceOrderMapper.selectManageOrderList4(orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders4) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    getManageResultStatus(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            case 5:
                List<MaintenanceOrder> maintenanceOrders5 = maintenanceOrderMapper.selectManageOrderList5(orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders5) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    getManageResultStatus(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            case 6:
                List<MaintenanceOrder> maintenanceOrders6 = maintenanceOrderMapper.selectManageOrderList6(orderStatus);
                for (MaintenanceOrder maintenanceOrder : maintenanceOrders6) {
                    MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
                    BeanUtils.copyProperties(maintenanceOrder, maintenanceOrderVo);
                    getManageResultStatus(maintenanceOrder, maintenanceOrderVo);
                    maintenanceOrderVoList.add(maintenanceOrderVo);
                }
                break;
            default:
                break;
        }
        return maintenanceOrderVoList;
    }

    private MaintenanceOrderVo getManageResultStatus(MaintenanceOrder maintenanceOrder, MaintenanceOrderVo maintenanceOrderVo) {
        maintenanceOrderVo.setLinkDeviceId(maintenanceOrder.getDeviceId());
        Integer preStatus = maintenanceOrder.getPreStatus();
        Integer wbStatus = maintenanceOrder.getWbStatus();
        switch (preStatus) {
            case 1:
                maintenanceOrderVo.setResultStatus(1);
                maintenanceOrderVo.setResultStatusMsg("待分配");
                break;
            case 2:
                switch (wbStatus) {
                    case 1:     //1待维修，2待确认（管理员待审核），3已完成，4已拒绝
                        maintenanceOrderVo.setResultStatus(2);
                        maintenanceOrderVo.setResultStatusMsg("待维修");
                        break;
                    case 2:
                        maintenanceOrderVo.setResultStatus(3);
                        maintenanceOrderVo.setResultStatusMsg("待审核");
                        break;
                    case 3:

                        maintenanceOrderVo.setResultStatus(4);
                        maintenanceOrderVo.setResultStatusMsg("已完成");

                        break;
                    case 4:
                        maintenanceOrderVo.setResultStatus(5);
                        maintenanceOrderVo.setResultStatusMsg("已驳回");
                        break;
                    default:
                        break;
                }
                break;
            case 3:
                maintenanceOrderVo.setResultStatus(6);
                maintenanceOrderVo.setResultStatusMsg("已忽略");
                break;
            default:
                break;
        }
        return maintenanceOrderVo;
    }




    private MaintenanceUser getMaintenanceUser(Integer customerUserId) throws Exception {
        MaintenanceUser maintenanceUser = maintenanceUserMapper.selectByCustomerUserId(customerUserId);
        if(maintenanceUser == null){
            throw new Exception("用户不存在");
        }
        return maintenanceUser;
    }

    private MaintenanceUser getManageMaintenanceUser(Integer customerUserId) throws Exception {
        MaintenanceUser maintenanceUser = maintenanceUserMapper.selectManageByCustomerUserId(customerUserId);
        if(maintenanceUser == null){
            throw new Exception("用户不存在");
        }
        return maintenanceUser;
    }

    private Boolean addOrderHistory(MaintenanceOrderHistory orderHistory){
        return maintenanceOrderHistoryMapper.insert(orderHistory) > 0;
    }

    @Transactional
    public void finish(Integer orderId, Integer wbStatus, Integer customerUserId) {
        //value 3已完成，4已拒绝
        try {
            MaintenanceOrder maintenanceOrder = maintenanceOrderMapper.selectById(orderId);
            MaintenanceUser maintenanceUser = maintenanceUserMapper.selectById(maintenanceOrder.getWbUserId());
            if(wbStatus !=3 && wbStatus !=4){
                throw new Exception();
            }
            maintenanceOrderMapper.finish(orderId, wbStatus);
            MaintenanceOrderHistory orderHistory = new MaintenanceOrderHistory();
            orderHistory.setOperateUserId(getManageMaintenanceUser(customerUserId).getId());
            orderHistory.setOrderId(orderId);
            orderHistory.setOperateAction(wbStatus ==3?OPRATE_FINISH:OPRATE_REFUSE);
            orderHistory.setOperateTime(new Date());
            if(!addOrderHistory(orderHistory)){
                throw new Exception("标记失败");
            }
            //解除维保人员绑定设备
            Integer unBindDeviceId = maintenanceOrder.getDeviceId();
            DevicePo devicePo = deviceMapper.selectById(unBindDeviceId);
            Integer hostDeviceId = devicePo.getHostDeviceId();
            DeviceTeamItemPo deviceTeamItemPo = null;
            if(hostDeviceId != null){
                List<DevicePo> devicePos = deviceMapper.queryChildDevice(hostDeviceId);
                List<Integer> childIdList = devicePos.stream().map(childDevice -> childDevice.getId()).collect(Collectors.toList());
                List<Integer> wbDeviceIdList = maintenanceOrderMapper.selectDeviceIdListByWbUserId(maintenanceOrder.getWbUserId());
                Boolean flag = false;
                for (Integer deviceId : wbDeviceIdList) {
                    if(childIdList.contains(deviceId) || deviceId == hostDeviceId){
                        flag = true;//不能删关系
                        break;
                    }
                }
                if(!flag){
                    deviceTeamItemPo = deviceTeamItemMapper.selectByJoinId(hostDeviceId, maintenanceUser.getCustomerUserId());
                }
            }else{
                deviceTeamItemPo = deviceTeamItemMapper.selectByJoinId(unBindDeviceId, maintenanceUser.getCustomerUserId());
            }
            if(deviceTeamItemPo!=null){
                deviceTeamItemMapper.deleteById(deviceTeamItemPo.getId());
            }
            //如果以拒绝，则重新生成订单
            if(wbStatus==4){
                MaintenanceOrder order  = new MaintenanceOrder();
                BeanUtils.copyProperties(maintenanceOrder, order);
                order.setFeedback(0);  //业主反馈状态：0初始状态，1已解决，2未解决
                order.setPreStatus(1);  //分配前，状态：1待审核（管理员待分配），2待维修，3已忽略
                order.setWbStatus(1);  //分配后，状态：0初始状态，1待维修，2待确认（管理员待审核），3已完成，4已拒绝
                order.setOrderTime(new Date()); //订单时间
                LocalDateTime now = LocalDateTime.now();
                //年月日时分秒毫秒
                String orderNo = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")) + afterAdd();
                order.setOrderNo(orderNo);
                order.setStatus(1);
                order.setPjStatus(0);
                order.setResultPhoto(null);
                order.setStar(null);
                order.setWbUserId(null);
                maintenanceOrderMapper.insert(order);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public MaintenanceUserMsgVo getUserMsg(Integer customerUserId) {
        MaintenanceUser userMsg = maintenanceUserMapper.getUserMsg(customerUserId);
        MaintenanceUserMsgVo maintenanceUserMsgVo = new MaintenanceUserMsgVo();
        BeanUtils.copyProperties(userMsg, maintenanceUserMsgVo);
        return maintenanceUserMsgVo;
    }

    public List<MaintenanceOrderVo> selectList(com.huanke.iot.manage.vo.request.device.wb.MaintenanceOrderRequest request, Integer customerId) {

        MaintenanceOrder order = new MaintenanceOrder();
        order.setOrderNo(request.getOrderNo());
        order.setLinkName(request.getLinkName());
        order.setCustomerId(customerId);
        Integer queryStatus = request.getStatus();
        if (queryStatus != null) {
            switch (queryStatus) {
                case 1: //待分配
                    order.setPreStatus(1);
                    break;
                case 2: //待维修
                    order.setPreStatus(2);
                    order.setWbStatus(1);
                    break;
                case 3: //已维修
                    order.setPreStatus(2);
                    order.setWbStatus(2);
                    break;
                case 4: //已完成
                    order.setWbStatus(3);
                    break;
                case 5: //已忽略
                    order.setWbStatus(4);
                    break;
                default:
                    break;
            }
        }


        Integer offset = (request.getPage() - 1) * request.getLimit();
        Integer limit = request.getLimit();

        //查询 维保订单列表
        List<MaintenanceOrder> maintenanceOrders = maintenanceOrderMapper.selectList(order, limit, offset);
        List<MaintenanceOrderVo> maintenanceOrderVoList = new ArrayList<>();
        for (MaintenanceOrder maintenanceOrder : maintenanceOrders) {
            MaintenanceOrderVo maintenanceOrderVo = new MaintenanceOrderVo();
            BeanUtils.copyProperties(maintenanceOrder  ,maintenanceOrderVo);
            getManageResultStatus(maintenanceOrder, maintenanceOrderVo);
            getLinkProject(maintenanceOrderVo);
            maintenanceOrderVoList.add(maintenanceOrderVo);
        }
        return maintenanceOrderVoList;
    }

    public void manageuser(Integer userId, BaseRequest<String> request) throws Exception {
            String openId = request.getValue();

            // 检查openId是否存在
            CustomerUserPo customerUserPo = customerUserMapper.selectByOpenId(openId);
            if(customerUserPo == null){
                throw new Exception("openId 不存在");
            }
            // 检查管理员是否存在
        MaintenanceUser maintenanceUser = maintenanceUserMapper.selectManageByCustomerUserId(customerUserPo.getId());
            if(maintenanceUser != null){
                throw new Exception("你已经是管理员，无需重复添加");
            }
        userManagerMapper.updateOpenId(userId, openId);
            User manageUser = userManagerMapper.selectByOpenId(openId);
            MaintenanceUser user = new MaintenanceUser();
            user.setName(manageUser.getUserName());
            user.setPhone(manageUser.getTelephone());
            user.setCustomerId(customerUserPo.getCustomerId());
            user.setManageUserId(manageUser.getId());
            user.setAdmin(manageUser.getUserName());
            user.setPasswd(manageUser.getPassword());
            user.setCustomerUserId(customerUserPo.getId());
            user.setRole(3);
            user.setStatus(1);
            user.setCreateTime(new Date());
            maintenanceUserMapper.insert(user);

    }

    @Transactional
    public void addWbUser(MaintenanceManageWbUserVo request) throws Exception {

        CustomerUserPo customerUserPo = customerUserMapper.selectByOpenId(request.getOpenId());
        if(customerUserPo == null){
            throw new Exception("openId 不存在");
        }
        MaintenanceUser maintenanceUser = maintenanceUserMapper.selectWbByCustomerId(customerUserPo.getId());
        if(maintenanceUser != null){
            throw new Exception("该用户已经是维保人员，请勿重复添加");
        }
        MaintenanceUser user = new MaintenanceUser();
        BeanUtils.copyProperties(request, user);
        user.setCustomerId(customerUserPo.getCustomerId());
        user.setCustomerUserId(customerUserPo.getId());
        user.setRole(2);
        user.setCreateTime(new Date());
        user.setStatus(1);
        maintenanceUserMapper.insert(user);
        //添加维保组
        DeviceTeamPo deviceTeamPo = new DeviceTeamPo();
        deviceTeamPo.setName("维保组");
        deviceTeamPo.setCustomerId(customerUserPo.getCustomerId());
        deviceTeamPo.setCreateUserId(customerUserPo.getId());
        deviceTeamPo.setMasterUserId(customerUserPo.getId());
        deviceTeamPo.setStatus(1);
        deviceTeamPo.setTeamStatus(1);
        deviceTeamPo.setTeamType(1);
        deviceTeamPo.setCreateTime(System.currentTimeMillis());
        deviceTeamMapper.insert(deviceTeamPo);
    }

    public void updateWbUser(MaintenanceManageWbUserVo request) {
        MaintenanceUser user = maintenanceUserMapper.selectById(request.getId());
        BeanUtils.copyProperties(request, user);
        maintenanceUserMapper.updateById(user);
    }

    public List<MaintenanceManageWbUserVo> selectWbUserList(MaintenanceWbUserRequest request, Integer customerId) {
        MaintenanceUser user = new MaintenanceUser();
        user.setName(request.getName());
        user.setPhone(request.getPhone());
        user.setCustomerId(customerId);
        user.setWorkStatus(request.getWorkStatus());
        Integer offset = (request.getPage() - 1) * request.getLimit();
        Integer limit = request.getLimit();

        //查询 维保订单列表
        List<MaintenanceManageWbUserVo> maintenanceUserVoList = maintenanceUserMapper.selectWbUserList(user, limit, offset);
        return maintenanceUserVoList;
    }

    @Transactional
    public void deleteWbUser(BaseRequest<Integer> request) {
        MaintenanceUser maintenanceUser = maintenanceUserMapper.selectById(request.getValue());
        maintenanceUserMapper.deleteWbUser(request.getValue());
        //删除维保组
        List<DeviceTeamPo> deviceTeamPos = deviceTeamMapper.selectByMasterUserId(maintenanceUser.getCustomerUserId());
        for (DeviceTeamPo deviceTeamPo : deviceTeamPos) {
            if(deviceTeamPo.getName().equals(WB_TEAM_NAME)){
                deviceTeamMapper.deleteById(deviceTeamPo.getId());
                break;
            }
        }
    }

    public List<MaintenanceOrderRecordHistoryVo> selectWbHistoryList(Integer orderId) {
        return maintenanceOrderHistoryMapper.getList(orderId);
    }


    public List<MaintenanceManageWbUserVo> selectWorkedWbUserList() {
        return maintenanceUserMapper.selectWorkedWbUserList();
    }

    public void addManageOrder(MaintenanceOrderRequest request) {
    }

    public List<MaintenanceMaterialVo> selectMaterialList(MaintenanceMaterialRequest request, Integer manageUserId) {
        MaintenanceMaterial material = new MaintenanceMaterial();
        material.setName(request.getName());
        material.setStatus(request.getStatus());
        material.setCustomerId(manageUserId);
        Integer offset = (request.getPage() - 1) * request.getLimit();
        Integer limit = request.getLimit();
        List<MaintenanceMaterial> maintenanceMaterials = maintenanceMaterialMapper.selectList(material, limit, offset);
        List<MaintenanceMaterialVo> maintenanceMaterialVoList = new ArrayList<>();
        for (MaintenanceMaterial maintenanceMaterial : maintenanceMaterials) {
            MaintenanceMaterialVo maintenanceMaterialVo = new MaintenanceMaterialVo();
            BeanUtils.copyProperties(maintenanceMaterial, maintenanceMaterialVo);
            maintenanceMaterialVoList.add(maintenanceMaterialVo);
        }
        return maintenanceMaterialVoList;
    }

    public void materialDelete(Integer materialId) {
        maintenanceMaterialMapper.deleteById(materialId);
    }

    public void materialUpdate(MaintenanceMaterialVo request) {
        MaintenanceMaterial material = new MaintenanceMaterial();
        BeanUtils.copyProperties(request, material);
        maintenanceMaterialMapper.updateById(material);
    }

    public void materialAdd(MaintenanceMaterialVo request) {
        MaintenanceMaterial material = new MaintenanceMaterial();
        BeanUtils.copyProperties(request, material);
        maintenanceMaterialMapper.insert(material);
    }

    public MaintenanceManageWbUserVo wbuserDetail(Integer wbUserId) {
        return maintenanceUserMapper.selectWbUserDetailById(wbUserId);

    }

    private MaintenanceOrderVo getLinkProject(MaintenanceOrderVo maintenanceOrderVo) {
        Integer deviceId = maintenanceOrderVo.getLinkDeviceId();
        DevicePo devicePo = deviceMapper.selectById(deviceId);
        if (devicePo != null && devicePo.getHostDeviceId() != null) {
            deviceId = devicePo.getHostDeviceId();
        }
        if (devicePo != null) {
            DeviceGroupItemPo deviceGroupItemPo = deviceGroupItemMapper.selectByDeviceId(deviceId);
            if (deviceGroupItemPo != null) {
                Integer groupId = deviceGroupItemPo.getGroupId();
                List<ProjectGroupsRsp> projectGroupsRsps = projectMapper.selectGroups(Lists.newArrayList(groupId));

                if (CollectionUtils.isNotEmpty(projectGroupsRsps)) {
                    //根据设备组查工程(特殊处理)
                    ProjectBaseInfo projectBaseInfo = projectMapper.selectOnlyOneByGroupId(projectGroupsRsps.get(0).getId());
                    if(projectBaseInfo != null){
                        maintenanceOrderVo.setLinkProjectId(projectBaseInfo.getId());
                    }
                    maintenanceOrderVo.setLinkProjectName(projectGroupsRsps.get(0).getName());
                }

            }

        }else{
            Integer linkProjectId = maintenanceOrderVo.getLinkProjectId();
            if(linkProjectId != null){
                ProjectBaseInfo projectBaseInfo = projectMapper.selectById(linkProjectId);
                maintenanceOrderVo.setLinkProjectName(projectBaseInfo.getName());
            }
        }
        return maintenanceOrderVo;
    }
}
